<template>
	<view class="custom_msg_to_component">
		<view class="custom_msg_to_component_content">
			<view class="custom_msg_to_component_content_item" v-for="(code, index) in codes" :key="'code_' + index" v-if="codes.length > 0">
				<view v-if="code.type === 'component' && code.content.indexOf('userName') > -1">
					<navigator :url="'../../pages/user/info?id=' + item.data.userId">{{ item.data.userName }}</navigator>
				</view>
				<view v-if="code.type === 'component' && code.content.indexOf('newsTitle') > -1">
					<navigator :url="'../../pages/index/view?id=' + item.data.newsId">{{ item.data.newsTitle }}</navigator>
				</view>
				<view v-if="code.type === 'component' && code.content.indexOf('${startTime}') > -1">({{ _plugins.dateFormate(item.data.startTime, 'yyyy-MM-dd hh:mm:ss') }})</view>
				<view v-if="code.type === 'component' && code.content.indexOf('${endTime}') > -1">({{ _plugins.dateFormate(item.data.endTime, 'yyyy-MM-dd hh:mm:ss') }})</view>
				<view v-if="code.type === 'text'">{{ code.content }}</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	props: {
		item: {
			type: Object,
			default() {
				return {};
			}
		}
	},
	data() {
		return {
			template: '',
			codes: []
		};
	},
	created() {
		let that = this;
		this.template = this.$props.item.message;
		this.parseTexts(this.template)
			.then(v => {
				that.codes = v;
			})
			.catch(v => {
				console.log(v);
			});
	},
	methods: {
		parseTexts(v) {
			let that = this;
			return new Promise((resolve, reject) => {
				try {
					let code = [];
					v.replace(/([^\${}]+)*(\${[^\${}]+})([^\${}]+)*/gim, function(a, b, c, d) {
						[b, c, d].forEach(n => {
							/\${[^\${}]+}/.test(n) ? code.push({ type: 'component', content: n }) : typeof n !== 'undefined' && code.push({ type: 'text', content: n });
						});
						return a;
					});
					resolve(code);
				} catch (e) {
					reject(e);
				}
			});
		}
	}
};
</script>

<style lang="less">
.custom_msg_to_component {
	.custom_msg_to_component_content {
		.custom_msg_to_component_content_item {
			display: inline;
			view {
				display: inline;
			}
			navigator {
				display: inline;
				/* text-decoration: underline; */
				color: #4CD964;
			}
		}
	}
}
</style>
